<template>
  <div class="register">
    <div class="register-container">
      <el-row>
        <el-col :span="12">
        <span class="_before" v-if="typeRef==1">企业认证</span>
        <span class="_before" v-if="typeRef==2">修改企业名称</span>
        </el-col>
        <el-col :span="12"></el-col>
      </el-row>

      <div style="width: 80%;margin: 50px ;min-height:1000px;">
        <el-steps style="min-width: 600px;width: 100%;margin-left: 50px;" :active="active" process-status="wait"
          align-center size="small">
          <el-step title="企业实名认证" />
          <el-step title="法定代表人认证" />
          <el-step title="管理员认证" v-if="typeRef==1" />
        </el-steps>

        <el-form v-if="active == 1" ref="companyRef" :model="companyData" :rules="companyRules" label-width="150px"
          label-position="right" style="margin:auto; width: 600px;margin-top: 50px;">
          <el-form-item v-if="typeRef==2" label="原企业名称：" prop="name">{{ nameUdat }}
          </el-form-item>
          <el-form-item label="营业执照：" prop="businessLicense">
            <licenseOcr ref="licenseRef" :needOcr="true" :drag="false" @ocrLicense="ocrLicense" @businessLicense='getBusinessLicense'>
            </licenseOcr>
          </el-form-item>
          <el-form-item label="统一社会信用代码：" prop="invoiceTaxnum">
            <el-input v-model="companyData.invoiceTaxnum" size="large" placeholder="请输入" />
          </el-form-item>
          <el-form-item :label="typeRef==1 ? '企业名称：':'变更后企业名称：'" prop="name">
            <el-input v-model="companyData.name" size="large" placeholder="请输入" />
          </el-form-item>
           <el-form-item label="企业简称：" prop="abbCompanyName">
            <el-input v-model="companyData.abbCompanyName" size="large" maxlength="20" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="法定代表人：" prop="identity">
            <el-input v-model="companyData.identity" size="large" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="成立日期：" prop="foundingTime">
            <el-date-picker v-model="companyData.foundingTime" type="date" placeholder="" size="large" />
          </el-form-item>
          <!-- <el-form-item label="营业期限：" prop="businessHours">
            <el-input v-model="companyData.businessHours" size="large" placeholder="请输入" />
          </el-form-item> -->
          <el-form-item label="主营业务：" prop="mainBusiness">
            <!-- <el-input v-model="companyData.mainBusiness" size="large" placeholder="请输入" /> -->
            <!-- 5-贷代 10-集装箱公司 15-箱贸易 20-集卡车队 25-堆场 -->
            <el-select v-model="companyData.mainBusiness" size="large" multiple placeholder="请选择">
              <el-option v-for="item in mainBusinessList"  :value="{ value: item.value, label: item.label}" :key="item.value" :label="item.label">
            </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label-width="0">
            <el-button :loading="loading" @click="handleNextStep" type="primary" size="large"
              style="margin-top: 20px;width: 100%;">
              <span> 下一步 </span>
            </el-button>
          </el-form-item>
        </el-form>
        <el-form v-if="active == 2" ref="legalManRef" :model="legalMan" :rules="legalManRules" label-width="200px"
          label-position="right" style="margin:auto; width: 600px;margin-top: 50px;">
          <el-form-item label="法定代表人身份证照片：" prop="username">
            <IDCardOcr ref="IDCardRef" :title="'上传身份证人像面照片'" :idCardType="1" :idIDCard="true" :needOcr="false" :drag="false" :isFronface="true" 
            @ocrIDCard="ocrIDCardFront" @idCardData="idCardData" @idCardDataLinkZM ='getIdCardDataLinkZM'>
            </IDCardOcr>
          </el-form-item>
          <el-form-item label="" prop="username">
            <IDCardOcr ref="IDCardRef" :title="'上传身份证国徽面照片'" :idCardType="1" :idIDCard="true" :needOcr="false" :drag="false" :isFronface="false"
              @ocrIDCard="ocrIDCard"  @idCardData="idCardData" @idCardDataLinkFM ='getIdCardDataLinkFM'>
            </IDCardOcr>
          </el-form-item>
          <el-form-item label="法定代表人身份证号：" prop="idNo">
            <el-input v-model="legalMan.idNo" size="large" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="法定代表人姓名：" prop="name">
            <el-input v-model="legalMan.name" size="large" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="发证机关：" prop="certificateOffice">
            <el-input v-model="legalMan.certificateOffice" size="large" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="有效期：" prop="validityPeriod">
            <el-date-picker v-model="legalMan.validityPeriod" type="daterange" placeholder="" size="large" :start-placeholder='legalMan.startTime' :end-placeholder='legalMan.endTime'/>
          </el-form-item>
          <el-form-item label="手机号：" prop="tel">
            <el-col :span="16"><el-input v-model="legalMan.tel" size="large" placeholder="请输入" /></el-col>
            <el-col :span="8" align="right"> <el-button type="primary" :disabled="countdownPhone > 0" size="large" @click="getMessageCode">{{ countdownPhone > 0 ? countdownPhone + '秒' : '验证码' }}</el-button></el-col>
          </el-form-item>
          <el-form-item label="验证码：" prop="code">
            <el-input v-model="legalMan.code" size="large" placeholder="请输入" />
          </el-form-item>
          <el-form-item :label-width="0" v-if="typeRef==1">
            <el-button :loading="loading" @click="handleNextStep" type="primary" size="large"
              style="margin-top: 20px;width: 100%;">
              <span> 下一步 </span>
            </el-button>
          </el-form-item>
           <el-form-item  v-if="typeRef==2">
            <div>
              <el-checkbox v-model="param.isAgree" />
              <span style="font-size: 12px;">
                我已阅读并同意
                <a href="#">《智箱界供应链平台服务协议》</a>
                <a href="#">《用户隐私》</a>
              </span>
            </div>
          </el-form-item>
           <el-form-item :label-width="0" v-if="typeRef==2">
            <el-button :loading="loading" @click="handleSubmit(2)" type="primary" size="large"
              style="margin-top: 20px;width: 100%;">
              <span> 提交 </span>
            </el-button>
          </el-form-item>
        </el-form>
        <el-form v-if="active == 3" ref="adminRef" :model="adminData" :rules="adminRules" label-width="150px"
          label-position="right" style="margin:auto; width: 600px;margin-top: 50px;">
          <el-form-item label="管理员身份证照片：" prop="username">
            <IDCardOcr ref="IDCardRef" :title="'上传身份证人像面照片'" :idCardType="2" :idIDCard="true" :isFronface="true" :needOcr="false" :drag="false" @idCardDataGL='idCardDataGL' @ocrLicense="ocrLicense" @idCardDataLink="idCardDataLink" @idCardDataGLLinkZM="getIdCardDataGLLinkZM">
            </IDCardOcr>
          </el-form-item>
          <el-form-item label="" prop="username">
            <IDCardOcr ref="IDCardRef" :title="'上传身份证国徽面照片'" :idCardType="2" :idIDCard="true" :isFronface="false"  :needOcr="false" :drag="false" @idCardDataGL='idCardDataGL'  @ocrLicense="ocrLicense"  @idCardDataGLLinkFM="getIdCardDataGLLinkFM">
            </IDCardOcr>
          </el-form-item>
          <el-form-item label="管理员身份证号：" prop="idNo">
            <el-input v-model="adminData.idNo" size="large" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="管理员姓名：" prop="name">
            <el-input v-model="adminData.name" size="large" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="发证机关：" prop="issuedBy">
            <el-input v-model="adminData.issuedBy" size="large" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="有效期：" prop="validityPeriod">
            <el-date-picker v-model="adminData.validityPeriod" type="daterange" placeholder="" size="large" :start-placeholder='adminData.startTime' :end-placeholder='adminData.endTime'/>
          </el-form-item>
          <el-form-item>
            <div>
              <el-checkbox v-model="param.isAgree" />
              <span style="font-size: 12px;">
                我已阅读并同意
                <a href="#">《智箱界供应链平台服务协议》</a>
                <a href="#">《用户隐私》</a>
              </span>
            </div>
          </el-form-item>
          <el-form-item :label-width="0">
            <el-button :loading="loading" @click="handleSubmit(1)" type="primary" size="large"
              style="margin-top: 20px;width: 100%;">
              <span> 提 交 </span>
            </el-button>
          </el-form-item>
        </el-form>

      </div>

    </div>
  </div>
</template>

<script setup lang="ts">
import IDCardOcr from '@/components/upload/IDCardOcr.vue'
import licenseOcr from '@/components/upload/licenseOcr.vue'
import IDCardslot from '@/components/upload/IDCardslot.vue'
// import logo from '@/assets/logo/chengzhi.png'
import { ElMessage, ElMessageBox } from "element-plus";
import { smsCodeIdentity,sms_code_identity, sms_code_conservator, sms_code_tourist } from '@/api/sms/index'
import { getUserData, registerTourist } from '@/api/user/index'
import { addSysCompany, updateSysCompanyAuthentication,updateSysCompany, ocrIDCardVerify, ocrLicenseVerify } from '@/api/company/index'
import { getCurrentInstance, reactive, ref ,onMounted} from 'vue'
import { useRouter,useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
import useUserStore from '@/store/modules/user'
import en from '../../../locales/en';
const userStore = useUserStore()
const typeRef=ref(1) //1 添加 2编辑
const nameUdat=ref('')
const companyId=ref('')
onMounted(() => {
  if(route.query.type){
    typeRef.value=route.query.type
    nameUdat.value=route.query.name
    companyId.value=route.query.id
  }
})
const param = ref({
  username: "",
  password: "",
  confirmPassword: "",
  select: '1',
  mobile: "",
  code: "",
  isAgree: false
});
const mainBusinessList=[
    { value: 5, label: '租箱企业' },
    { value: 10, label: '集装箱公司' },
    { value: 15, label: '集卡公司' },
    { value: 20, label: '堆场公司' },
  ]
const active = ref(1)

const registerRules = {
  username: [
    { required: true, trigger: "blur", message: "请输入您的账号" },
    { min: 6, max: 25, message: "用户账号长度必须介于 6 和 25 之间", trigger: "blur" },
    { pattern: /^[a-zA-Z0-9_]+$/, message: "请输入大小写字母、数字、下划线", trigger: "blur" }
  ],
  password: [
    { required: true, trigger: "blur", message: "请输入您的密码" },
    { min: 8, max: 20, message: "用户密码长度必须介于 8 和 20 之间", trigger: "blur" },
    { pattern: /^[^<>"'|\\]+$/, message: "请输入大小写字母、数字、特殊符号", trigger: "blur" }
  ],
  confirmPassword: [
    { required: true, trigger: "blur", message: "请再次输入您的密码" },
  ],
  mobile: [{ required: true, trigger: "blur", message: "请输入手机号" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }]
};


//下一步
const loading = ref(false);
function handleNextStep() {
  // const data = {
  //   "name": "河南亚航国际货运代理有限公司",
  //   "orgCode": "91410105671693661Y",
  //   "legalRepName": "武金磊"
  // }
  if (active.value == 1) {
    const data = {
      "name": companyData.name,
      "orgCode": companyData.invoiceTaxnum,
      "legalRepName": companyData.identity,
    }
    if(companyData.abbCompanyName==''){
        return ElMessage.warning('企业简称不能为空！')
    }
    ocrLicenseVerify(data).then(res => {
      active.value++
    })
  }else if (active.value == 2) {
    const data = {
      "idNo": legalMan.idNo,
      "name": legalMan.name
    }
    ocrIDCardVerify(data).then(res => {
      active.value++
    })
  }else{

  // return proxy.$refs.registerRef.validate(valid => {
  //   if (valid) {
  //     if (!param.value.isAgree) {
  //       return ElMessage.warning('请选择同意平台协议！')
  //     }
  //     loading.value = true;
  //     const data = {
  //       username: param.value.username,
  //       password: param.value.password,
  //       verifyPassWord: param.value.confirmPassword,
  //       code: param.value.code,
  //       mobile: param.value.mobile,
  //     }
  //     registerTourist(data).then(res => {
  //       const username = param.value.username;
  //       ElMessageBox.alert("<font color='red'>恭喜你，您的账号 " + username + " 注册成功！</font>", "系统提示", {
  //         dangerouslyUseHTMLString: true,
  //         type: "success",
  //       }).then(() => {
  //         router.push("/login");
  //       }).catch(() => { });
  //     }).catch(() => {
  //       ElMessage.error('抱歉哦！注册失败')
  //       loading.value = false;
  //     });
  //   }
  // });
  }

}

// 发票识别
const companyData = reactive({
  invoiceTaxnum: '',
  name: '',
  identity: '',
  foundingTime: '',
  businessHours: '',
  abbCompanyName:'',
  mainBusiness: [],
  businessLicense:[]
})
const getBusinessLicense = (row)=>{
  console.log('营业执照',row)
  companyData.businessLicense.push(row)
}

const ocrLicense = (data: any) => {
  console.log(11,data)
  let val=data.data
  companyData.invoiceTaxnum = val.certNo
  companyData.name = val.name
  companyData.identity = val.legalRepName
  companyData.foundingTime = val.establishDate.replace(/(\d{4})年(\d{2})月(\d{2})日/, '$1-$2-$3');
  companyData.businessHours = val.validTerm
  companyData.mainBusiness=[]
  // return invoice.value.invoiceNo = val.data.invoiceNo
}

// 身份证识别 zheng
const legalMan = reactive({
  name: '',
  idNo: '',
  sex: '',
  birthday: '',
  address: '',
  nation: '',
  certificateOffice:"",
  validityPeriod:'',
  tel:'',
  code:'',
  identityPhoto:[],
  startTime:'',
  endTime:''
  // identityPhotoZM:'',
  // identityPhotoFM:{}
})
const idCardData = (data)=>{  //法人
  console.log("法人身份证信息",data)
  let row=data.data
legalMan.name=row.name
legalMan.idNo=row.idNo
legalMan.sex=row.gender
legalMan.birthday=row.birthDay
legalMan.address=row.address
legalMan.nation=row.nation
legalMan.certificateOffice = row.issuedBy
legalMan.validityPeriod = row.validityPeriod
legalMan.startTime=row.validityPeriod.split('-')[0]?.replace(/\./g,'-')
legalMan.endTime=row.validityPeriod.split('-')[1]?.replace(/\./g,'-')

}

const getIdCardDataLinkZM = (row)=> {
    const rowObj =  Object.assign(row,{type:1})
    legalMan.identityPhoto.push(rowObj)
}


const getIdCardDataLinkFM = (row)=> {
    const rowObj =  Object.assign(row,{type:2})
    legalMan.identityPhoto.push(rowObj)
}

const adminData = reactive({
idNo:'',
name:'',
issuedBy:'',
validityPeriod:'',
identityPhoto:[],
startTime:'',
endTime:''
// identityPhotoZM:{
//   type:Array,
//   default:()=> []
// } 
// identityPhotoFM:{
//   type:Array,
//   default:()=> []
// }
})
const idCardDataGL =(data) =>{ //管理员
  // console.log("管理员身份证信息",rew)
  let rew=data.data
adminData.idNo=rew.idNo
adminData.name=rew.name
adminData.issuedBy=rew.issuedBy
adminData.validityPeriod=rew.validityPeriod
adminData.startTime=rew.validityPeriod.split('-')[0]?.replace(/\./g,'-')
adminData.endTime=rew.validityPeriod.split('-')[1]?.replace(/\./g,'-')

}

const getIdCardDataGLLinkZM = (row) => {
    const rowObj =  Object.assign(row,{type:1})
    adminData.identityPhoto.push(rowObj)
}


const getIdCardDataGLLinkFM = (row)=> {
    const rowObj =  Object.assign(row,{type:2})
    adminData.identityPhoto.push(rowObj)
}
function getMessageCode() {
  let data = {
    "mobile": legalMan.tel
  }
  console.log('data',data)
  sms_code_identity(data).then(res => {
    ElMessage.success("验证码发送成功！");
    sendVerificationCode()
  });
}

// 倒计时的秒数
const countdownPhone = ref(0);

// 发送验证码函数
const sendVerificationCode = () => {
   // 如果倒计时已经开始，则直接返回
   if (countdownPhone.value > 0) return;

    // 设置倒计时为60秒
    countdownPhone.value = 60;
    // 启动定时器，每秒减少一秒
    const timer = setInterval(() => {
      countdownPhone.value--;
        // 当倒计时结束时，清除定时器
        if (countdownPhone.value === 0) {
          clearInterval(timer);
        }
    }, 1000)
  
}
const ocrIDCardFront = (val: any) => {
  console.log(222, val)
}
const ocrIDCard = (val: any) => {
  console.log(111, val)
}



// 提交 

function handleSubmit(type) {
  if (!param.value.isAgree) {
        return ElMessage.warning('请选择同意平台协议！')
      }
    let mainBusinessFor=[]
   companyData.mainBusiness.forEach((item)=>{
      let obj={
        id:item.value,
        name: item.label,
      }
      mainBusinessFor.push(obj)
    })
    if(type==1){
       const data = {
        // id:6,
        userId:userStore.getUser().id,
        name: companyData.name,
        abbCompanyName:companyData.abbCompanyName,
        mainBusiness: JSON.stringify(mainBusinessFor),
        invoiceTaxnum: companyData.invoiceTaxnum,
        businessLicense: JSON.stringify(companyData.businessLicense),
        foundingTime: companyData.foundingTime,
        // businessHours: companyData.businessHours,
        identity: companyData.identity,
        identityPhoto: JSON.stringify(legalMan.identityPhoto),
        identityNo: legalMan.idNo,
        certificateOffice: legalMan.certificateOffice,
        startTime: legalMan.startTime,
        endTime: legalMan.endTime,
        mobile: legalMan.tel,
        code: legalMan.code,
        userIdentityPhoto: JSON.stringify(adminData.identityPhoto),
        userIdentityNo: adminData.idNo,
        userCertificateOffice: adminData.issuedBy,
        userStartTime: adminData.startTime,
        userEndTime: adminData.endTime,
        nickName:adminData.name
      }
      addSysCompany(JSON.stringify(data)).then(res => {
        ElMessage.success('恭喜您，认证成功,请等候审核结果！')
        router.push("/index")
      })
    }else{
       const data = {
        // id:6,
        id:companyId.value,
        name: companyData.name,
        abbCompanyName:companyData.abbCompanyName,
        mainBusiness: JSON.stringify(mainBusinessFor),
        invoiceTaxnum: companyData.invoiceTaxnum,
        businessLicense: JSON.stringify(companyData.businessLicense),
        foundingTime: companyData.foundingTime,
        // businessHours: companyData.businessHours,
        identity: companyData.identity,
        identityPhoto: JSON.stringify(legalMan.identityPhoto),
        identityNo: legalMan.idNo,
        certificateOffice: legalMan.certificateOffice,
        startTime: legalMan.startTime,
        endTime: legalMan.endTime,
        mobile: legalMan.tel,
        code: legalMan.code,
      }
      updateSysCompanyAuthentication(JSON.stringify(data)).then(res => {
        ElMessage.success('恭喜您，修改成功,请等候审核结果！')
        router.push("/index")
      })
    }
 
} 
</script>

<style lang='scss' scoped>
a {
  text-decoration: underline;
  color: #409eff;
}

.register {
  width: 100%;
  min-height: 1000px;
  background-color: #eee;

  .register-header {
    width: 100%;
    height: 80px;
    background-color: white;
    box-sizing: border-box;
    padding: 20px;
  }

  .register-container {
    min-width: 1000px;
    background-color: white;
    margin: auto;
    box-sizing: border-box;
    padding: 20px 30px;
    margin-top: 20px;
  }

  .register-header-logo {
    float: left;
    margin-left: 10%;
  }

  .register-code {
    width: 35%;
    height: 40px;
    float: right;
  }
}
</style>
